package main.java.com.healthy.dao.impl;

import main.java.com.healthy.dao.NutritionGoalDAO;
import main.java.com.healthy.entity.NutritionGoal;
import main.java.com.healthy.util.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 营养目标数据访问实现类
 */
public class NutritionGoalDAOImpl implements NutritionGoalDAO {

    private static final String GOAL_FILE = "data/nutrition_goals.dat";
    private List<NutritionGoal> goals;

    public NutritionGoalDAOImpl() {
        loadGoals();
    }

    @Override
    public boolean addGoal(NutritionGoal goal) {
        try {
            // 生成唯一目标ID
            if (goal.getGoalId() == null || goal.getGoalId().isEmpty()) {
                goal.setGoalId(generateGoalId());
            }

            // 检查用户是否已有目标
            if (hasGoal(goal.getUserId())) {
                System.out.println("用户已有营养目标，请使用更新操作");
                return false;
            }

            goals.add(goal);
            return saveGoals();
        } catch (Exception e) {
            System.err.println("添加营养目标失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean updateGoal(NutritionGoal goal) {
        try {
            for (int i = 0; i < goals.size(); i++) {
                if (goals.get(i).getGoalId().equals(goal.getGoalId())) {
                    goals.set(i, goal);
                    return saveGoals();
                }
            }
            return false;
        } catch (Exception e) {
            System.err.println("更新营养目标失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean deleteGoal(String goalId) {
        try {
            boolean removed = goals.removeIf(goal -> goal.getGoalId().equals(goalId));
            if (removed) {
                return saveGoals();
            }
            return false;
        } catch (Exception e) {
            System.err.println("删除营养目标失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public NutritionGoal getGoalByUserId(String userId) {
        return goals.stream()
                .filter(goal -> goal.getUserId().equals(userId) && goal.isActive())
                .findFirst()
                .orElse(null);
    }

    @Override
    public boolean hasGoal(String userId) {
        return goals.stream()
                .anyMatch(goal -> goal.getUserId().equals(userId) && goal.isActive());
    }

    @Override
    public boolean setGoalActive(String userId, boolean active) {
        try {
            NutritionGoal goal = getGoalByUserId(userId);
            if (goal != null) {
                goal.setActive(active);
                return updateGoal(goal);
            }
            return false;
        } catch (Exception e) {
            System.err.println("设置目标激活状态失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 生成唯一目标ID
     */
    private String generateGoalId() {
        return "GOAL_" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 加载营养目标数据
     */
    @SuppressWarnings("unchecked")
    private void loadGoals() {
        try {
            Object data = FileUtil.readObject(GOAL_FILE);
            if (data instanceof List) {
                goals = (List<NutritionGoal>) data;
            } else {
                goals = new ArrayList<>();
            }
        } catch (Exception e) {
            System.err.println("加载营养目标数据失败: " + e.getMessage());
            goals = new ArrayList<>();
        }
    }

    /**
     * 保存营养目标数据
     */
    private boolean saveGoals() {
        try {
            return FileUtil.writeObject(GOAL_FILE, goals);
        } catch (Exception e) {
            System.err.println("保存营养目标数据失败: " + e.getMessage());
            return false;
        }
    }
}